#include "ToJSON.h"


ToJSON::ToJSON(void)
{
}


ToJSON::~ToJSON(void)
{
}

void ToJSON::startArray()
{
}
void ToJSON::closeArray()
{
}
void ToJSON::addSepArray()
{
}
void ToJSON::addWord(char *str)
{
}
void ToJSON::parseLinkage(Linkage linkage)
{
	char connector[MAX_TOKEN_LENGTH];
	Sublinkage *sublinkage=&(linkage->sublinkage[linkage->current]);
	int N_links = sublinkage->num_links;
	Link **ppla = sublinkage->link;
	Dictionary dict = linkage->sent->dict;
	Parse_Options opts = linkage->opts;
	int N_words_to_print;
	Sentence sent = linkage->sent;

	jsonr = "{";
	int i = 0;
	fprintf(stderr, "{words : [");
	jsonr += "words : [";
	for (; i<sent->length - 1; i++) {
		jsonr += sent->word[i].string;
		jsonr += ", ";
		fprintf(stderr, "%s, ", sent->word[i].string);
	}
	jsonr += sent->word[i].string;
	fprintf(stderr, "%s", sent->word[i].string);
	jsonr += "],";
	fprintf(stderr, "],\n");

	int link = 0;
	std::stringstream out;
	jsonr += "links : [";
	for (; link<N_links-1; link++) {
		jsonr += "{left: ";
		out << ppla[link]->l;
		jsonr += out.str();
		out.str(std::string());
		jsonr += ", right: ";
		out << ppla[link]->r;
		jsonr += out.str(); 
		out.str(std::string());
		jsonr += ", name: ";
		jsonr += ppla[link]->name;
		jsonr += "},";
	}
	jsonr += "{left: ";
	out << ppla[link]->l;
	jsonr += out.str(); 
	out.str(std::string());
	jsonr += ", right: ";
	out << ppla[link]->r;
	jsonr += out.str(); 
	out.str(std::string());
	jsonr += ", name: ";
	jsonr += ppla[link]->name;
	jsonr += "}]}";
	fprintf(stderr, "%s\n",jsonr.c_str());
}
void ToJSON::analyse(char * s)
{
	Dictionary    dict;
    Parse_Options opts;
	Sentence      sent;
    Linkage       linkage;
    char *        diagram;
    int           num_linkages;
	const char *  input_string = s;
	//std::string res = "nothing";

	
	fflush(stderr);
	opts  = parse_options_create();
    dict  = dictionary_create("C:\\Users\\IBM_ADMIN\\link-grammar\\data\\en\\4.0.dict", "C:\\Users\\IBM_ADMIN\\link-grammar\\data\\en\\4.0.knowledge", NULL, "C:\\Users\\IBM_ADMIN\\link-grammar\\data\\en\\4.0.affix");
	sent = sentence_create(input_string, dict);
	num_linkages = sentence_parse(sent, opts);
	
	if (num_linkages > 0) {
		
		linkage = linkage_create(0, sent, opts);
		//diagram = linkage_print_diagram(linkage);
		parseLinkage(linkage);
		printf("%s\n", diagram = linkage_print_diagram(linkage));
		//delete(diagram);
		linkage_delete(linkage);
		sentence_delete(sent);
    }


	parse_options_delete(opts);
	dictionary_delete(dict);

	printf ("Bye.\n");
}


static int main(int argc, char * argv[])
{
	ToJSON *tj = new ToJSON();
	tj->analyse(argv[1]);
}